package com.xxx.codec;

import com.xxx.serializer.Serializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToByteEncoder;

import java.util.List;

/**
 * Created by louisyuu on 2020/4/20 下午3:05
 * 现在传输的是RpcRequest, 需要将消息转化成对象
 */

public class RpcDecoder extends ByteToMessageDecoder {


    private Class<?> clazz;

    private Serializer serializer;


    public RpcDecoder(Class<?> clazz, Serializer serializer) {
        this.clazz = clazz;
        this.serializer = serializer;

    }


    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        if (clazz != null && serializer != null) {

            if (byteBuf.readableBytes() <= 0) {
                System.out.println("<=0");
                return;
            }
            byte[] payloads = new byte[byteBuf.readableBytes()];


            byteBuf.getBytes(0, payloads);

            /**
             * 防止io.netty.handler.codec.DecoderException: RpcDecoder.decode() did not read anything but decoded a message.
             */
            byteBuf.skipBytes(byteBuf.readableBytes());
            Object res = serializer.deserialize(clazz, payloads);

            if (res != null) {
                list.add(res);
            }
        }

    }


}
